package com.pig.graduate.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig.graduate.common.constant.Constant;
import com.pig.graduate.domain.sys.SysRole;
import com.pig.graduate.domain.sys.SysUser;
import com.pig.graduate.domain.sys.SysUserRole;
import com.pig.graduate.result.MyResult;
import com.pig.graduate.service.sys.SysRoleMenuService;
import com.pig.graduate.service.sys.SysRoleService;
import com.pig.graduate.service.sys.SysUserRoleService;
import com.pig.graduate.service.sys.SysUserService;
import com.pig.graduate.util.DateUtil;
import com.pig.graduate.util.RedisUtil;
import com.pig.graduate.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.util.*;

/**
 * 用户Controller控制器
 */

@Api(tags = {"用户管理"}, description = "用户管理")
@RestController
@RequestMapping("/sys/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${avatarImagesFilePath}")
    private String avatarImagesFilePath;


    /**
     * 验证用户名
     * @param sysUser
     * @return
     */
    @ApiOperation(value = "验证用户名",notes = "验证用户名")
    @PostMapping("/checkUserName")
//    @PreAuthorize("hasAuthority('system:user:query')")
    public MyResult checkUserName(@RequestBody SysUser sysUser){
        if(sysUserService.getUserByUsername(sysUser.getUsername())==null){
            return MyResult.success();
        }else{
            return MyResult.error();
        }
    }

    @ApiOperation(value = "用户列表",notes = "用户列表")
    @PostMapping("/list")
    public MyResult list(@RequestBody SysUser sysUser){
        Page<SysUser> userPage = new Page<>(sysUser.getPageNum(),sysUser.getPageSize());
        Page<SysUser> page = new LambdaQueryChainWrapper<SysUser>(sysUserService.getBaseMapper())
                .like(SysUser::getUsername,sysUser.getUsername())
                .like(SysUser::getPhoneNumber,sysUser.getPhoneNumber())
                .like(SysUser::getStatus,sysUser.getStatus())
                .page(userPage);
        for(SysUser user:page.getRecords()){
            // 获取角色
            List<SysRole> roleList = sysRoleService.list(new QueryWrapper<SysRole>().inSql("id", "select role_id from sys_user_role where user_id=" + user.getId()));
            // 设置角色
            // user.setRoles(roleList.stream().map(SysRole::getName).collect(Collectors.joining(",")));
            user.setSysRoleList(roleList);
        }
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("userList",page);
        return MyResult.success(resultMap);
    }

    /**
     * 添加或者修改
     * @param sysUser
     * @return
     */
    @ApiOperation(value = "添加修改",notes = "添加修改")
    @PostMapping("/saveAndUpdate")
//    @PreAuthorize("hasAuthority('system:user:add')"+"||"+"hasAuthority('system:user:edit')")
    public MyResult saveAndUpdate(@RequestBody @Valid SysUser sysUser){
        if(sysUser.getId()==null || sysUser.getId()==0){
            sysUser.setCreateTime(new Date());
            sysUser.setPassword(bCryptPasswordEncoder.encode(sysUser.getPassword()));
            sysUserService.save(sysUser);
        }else{
            sysUser.setUpdateTime(new Date());
            sysUserService.updateById(sysUser);
        }
        List<SysUserRole> userRoleList = new ArrayList<>();
        for (Long sysRoleId : sysUser.getSysRoleIds()) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(sysRoleId);
            sysUserRole.setUserId(sysUser.getId());
            userRoleList.add(sysUserRole);
        }
        sysUserRoleService.saveBatch(userRoleList);
        redisUtil.removeByPrex(Constant.AUTHORITY_KEY);
        return MyResult.success();
    }

    @ApiOperation(value = "修改",notes = "修改")
    @PostMapping("/updateUser")
//    @PreAuthorize("hasAuthority('system:user:add')"+"||"+"hasAuthority('system:user:edit')")
    public MyResult updateUser(@RequestBody @Valid SysUser sysUser){
        SysUser user = sysUserService.getById(sysUser.getId());
        user.setNickName(sysUser.getNickName());
        user.setPhoneNumber(sysUser.getPhoneNumber());
        user.setSex(sysUser.getSex());
        user.setEmail(sysUser.getEmail());
        user.setUpdateTime(new Date());
        sysUserService.updateById(sysUser);
        return MyResult.success();
    }
    /**
     * 修改密码
     * @param sysUser
     * @return
     */
    @ApiOperation(value = "修改密码",notes = "修改密码")
    @PostMapping("/updateUserPwd")
//    @PreAuthorize("hasAuthority('system:user:edit')")
    public MyResult updateUserPwd(@RequestBody SysUser sysUser){
        SysUser currentUser = sysUserService.getById(sysUser.getId());
        if(bCryptPasswordEncoder.matches(sysUser.getOldPassword(),currentUser.getPassword())){
            currentUser.setPassword(bCryptPasswordEncoder.encode(sysUser.getNewPassword()));
        }else{
            return MyResult.error("旧密码填写错误！");
        }
        sysUserService.updateById(currentUser);
        return MyResult.success();
    }

    /**
     * 更新status状态
     * @param id
     * @param status
     * @return
     */
    @ApiOperation(value = "状态",notes = "状态")
    @GetMapping("/updateStatus/{id}/status/{status}")
//    @PreAuthorize("hasAuthority('system:user:edit')")
    public MyResult updateStatus(@PathVariable(value = "id")Integer id,@PathVariable(value = "status")String status){
        SysUser sysUser = sysUserService.getById(id);
        sysUser.setStatus(status);
        sysUserService.saveOrUpdate(sysUser);
        redisUtil.removeByPrex(Constant.AUTHORITY_KEY);
        return MyResult.success();
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id查询",notes = "根据id查询")
    @GetMapping("/{id}")
//    @PreAuthorize("hasAuthority('system:user:query')")
    public MyResult findById(@PathVariable(value = "id")Integer id){
        SysUser sysUser = sysUserService.getById(id);
        List<SysRole> roleList = sysRoleService.list(new QueryWrapper<SysRole>().inSql("id", "select role_id from sys_user_role where user_id=" + id));
        sysUser.setSysRoleList(roleList);
        Map<String,Object> map=new HashMap<>();
        map.put("sysUser",sysUser);
        return MyResult.success(map);
    }

    /**
     * 重置密码
     * @param id
     * @return
     */
    @ApiOperation(value = "重置密码",notes = "重置密码")
    @GetMapping("/resetPassword/{id}")
//    @PreAuthorize("hasAuthority('system:user:edit')")
    public MyResult resetPassword(@PathVariable(value = "id")Integer id){
        SysUser sysUser = sysUserService.getById(id);
        sysUser.setPassword(bCryptPasswordEncoder.encode(Constant.DEFAULT_PASSWORD));
        sysUser.setUpdateTime(new Date());
        sysUserService.updateById(sysUser);
        return MyResult.success();
    }


    /**
     * 修改用户头像
     * @param sysUser
     * @return
     */
    @ApiOperation(value = "修改用户头像",notes = "修改用户头像")
    @PostMapping("/updateAvatar")
//    @PreAuthorize("hasAuthority('system:user:edit')")
    public MyResult updateAvatar(@RequestBody SysUser sysUser){
        SysUser currentUser = sysUserService.getById(sysUser.getId());
        currentUser.setAvatar(sysUser.getAvatar());
        sysUserService.updateById(currentUser);
        return MyResult.success();
    }

    /**
     * 上传用户头像图片
     * @param file
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "上传用户头像",notes = "上传用户头像")
    @PostMapping("/uploadImage")
//    @PreAuthorize("hasAuthority('system:user:edit')")
    public Map<String,Object> uploadImage(MultipartFile file)throws Exception{
        Map<String,Object> resultMap=new HashMap<>();
        if(!file.isEmpty()){
            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            String suffixName=originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName= DateUtil.getCurrentDateStr()+suffixName;
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(avatarImagesFilePath+newFileName));
            resultMap.put("code",200);
            resultMap.put("msg","上传成功");
            Map<String,Object> dataMap=new HashMap<>();
            dataMap.put("title",newFileName);
            dataMap.put("src","/image/userAvatar/"+newFileName);
            resultMap.put("data",dataMap);
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (!(authentication instanceof AnonymousAuthenticationToken)) {
                String currentUserName = authentication.getName();
                SysUser currentUser = sysUserService.getUserByUsername(currentUserName);
                currentUser.setAvatar("/image/userAvatar/"+newFileName);
                sysUserService.updateById(currentUser);
            }
        }
        return resultMap;
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @ApiOperation(value = "删除",notes = "删除")
    @Transactional
    @PostMapping("/delete")
//    @PreAuthorize("hasAuthority('system:user:delete')")
    public MyResult delete(@RequestBody Long[] ids){
        sysUserService.removeByIds(Arrays.asList(ids));
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("user_id",ids));
        redisUtil.removeByPrex(Constant.AUTHORITY_KEY);
        return MyResult.success();
    }

    /**
     * 用户角色授权
     * @param userId
     * @param roleIds
     * @return
     */
    @ApiOperation(value = "用户角色授权",notes = "用户角色授权")
    @Transactional
    @PostMapping("/grantRole/{userId}")
//    @PreAuthorize("hasAuthority('system:user:role')")
    public MyResult grantRole(@PathVariable("userId") Long userId,@RequestBody Long[] roleIds){
        List<SysUserRole> userRoleList=new ArrayList<>();
        Arrays.stream(roleIds).forEach(r -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(r);
            sysUserRole.setUserId(userId);
            userRoleList.add(sysUserRole);
        });
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id",userId));
        sysUserRoleService.saveBatch(userRoleList);
        redisUtil.removeByPrex(Constant.AUTHORITY_KEY);
        return MyResult.success();
    }


}
